// pages/resume/search/search.js
import { $wuxCalendar} from '../../../wux-components/index'
import {
  salary,
  edu,
  jobIntention,
  homeAddress,
  workExp,
  clearingWay
} from '../../../utils/base-data.js'
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    kindText: '职位',
    kindId: 0,
    isOpen: false,
    inputText: '',
    posPage: 1,
    posList: [],
    isLoadedPos: false,
    isFirstTipPos: true,

    isLoadedHourly: false,
    isFirstTipHourly: true,
    hourlyList: [],
    hourlyPage: 1,
    pageSize: 10,

    items: [{
      type: 'filter',
      label: '筛选',
      value: 'filter',
      groups: ['001'],
      children: [{
          type: 'radio',
          label: '性别',
          value: 'sex',
          children: [{
            label: '男',
            value: '1'
          }, {
            label: '女',
            value: '0'
          }]
        }, {
          type: 'radio',
          label: '意向行业',
          value: 'industry',
          children: []
        },
        {
          type: 'radio',
          label: '意向地点',
          value: 'workPlace',
          children: []
        }, {
          type: 'radio',
          label: '薪资范围',
          value: 'salary',
          children: []
        }, {
          type: 'radio',
          label: '求职状态',
          value: 'jobIntention',
          children: []
        }, {
          type: 'radio',
          label: '工作经验',
          value: 'workExp',
          children: []
        }, {
          type: 'radio',
          label: '学历',
          value: 'edu',
          children: []
        }, {
          type: 'radio',
          label: '居住地',
          value: 'hourseAddress',
          children: []
        }
      ]
    }],

    selectArr: [{
      checked: false
    }, {
      checked: false
    }, {
      checked: false
    }, {
      checked: false
    }], // 空闲-居住地-意向地点-结算方式

    filterHourlySpaceTime:[],
    filterHourlyHomeAddress:[],
    filterHourlyWorkPlace:[],
    filterHourlyClearingWay:[],
    filterHourlyHA:'',
    filterHourlyWP:'',
    filterHourlyCW: '',

    keepFilterData:{},
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.loadPosFilterData();
    this.initFilterHourlyData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    token = getApp().globalData.token;
    this.getPosList()
  },

  /**
   * 初始化小时工筛选源数据
   */
  initFilterHourlyData() {
    let _ha = JSON.parse(JSON.stringify(homeAddress))
    _ha.forEach(m => {
      this.data.filterHourlyHomeAddress.push(Object.assign(m, {
        checked: false,
        type: 1
      }))
    });

    homeAddress.forEach(m => {
      this.data.filterHourlyWorkPlace.push(Object.assign(m, {
        checked: false,
        type: 2
      }))
    });

    clearingWay.forEach(m => {
      this.data.filterHourlyClearingWay.push(Object.assign(m, {
        checked: false,
        type: 3
      }))
    });

  },

  loadHourlyFilterData(index) {
    let _temArr = [];
    index = Number(index);
    switch (index) {
      case 1:
        _temArr = this.data.filterHourlyHomeAddress;
        break;
      case 2:
        _temArr = this.data.filterHourlyWorkPlace;
        break;
      case 3:
        _temArr = this.data.filterHourlyClearingWay;
        break;
    }
    this.setData({
      filterList: _temArr
    });
    console.log(index,this.data.filterList)
  },

  loadPosFilterData() {
    let filterDddress = [];
    let filterIndustry = [];
    let filterSalary = [];
    let filterJontention = [];
    let filterWorkExp = [];
    let filterEdu = [];

    getApp().globalData.industryList.forEach(m => {
      filterIndustry.push({
        label: m.title,
        value: String(m.value)
      })
    })

    homeAddress.forEach(m => {
      filterDddress.push({
        label: m.title,
        value: String(m.value)
      })
    })

    salary.forEach(m => {
      filterSalary.push({
        label: m.title,
        value: String(m.value)
      })
    })

    jobIntention.forEach(m => {
      filterJontention.push({
        label: m.title,
        value: String(m.value)
      })
    })

    workExp.forEach(m => {
      if (m.value ==1) {
        filterWorkExp.push({
          label: '应届生',
          value: String(m.value)
        })
      }
      if (m.value > 2) {
        filterWorkExp.push({
          label: m.title,
          value: String(m.value)
        })
      }
    })

    edu.forEach(m => {
      filterEdu.push({
        label: m.title,
        value: String(m.value)
      })
    })

    this.setData({
      ['items[0].children[1].children']: filterIndustry,
      ['items[0].children[2].children']: filterDddress,
      ['items[0].children[3].children']: filterSalary,
      ['items[0].children[4].children']: filterJontention,
      ['items[0].children[5].children']: filterWorkExp,
      ['items[0].children[6].children']: filterEdu,
      ['items[0].children[7].children']: filterDddress,
    });
    this.setData({
      isOpenFilter: true
    });
  },

  onDropdown() {
    this.setData({
      isOpen: true
    })
  },

  onSelectPosHourly(e) {
    let value = parseInt(e.currentTarget.dataset.value);
    if (!value) {
      this.setData({
        kindId: 0,
        kindText: '职位',
        isOpen: false,
        isOpenFilter:true,
      })
    } else {
      this.setData({
        kindId: 1,
        kindText: '小时工',
        isOpen: false,
        isOpenFilter:false
      })
    }
    console.log(this.data.kindId);
  },  

  onInput(e) {
    this.setData({
      inputText: e.detail.value
    });
    this.getPosList(this.data.keepFilterData);
  },

  onChange(e) {
    const {
      checkedItems,
      items
    } = e.detail
    const params = {}
    checkedItems.forEach((n) => {
      if (n.checked) {
        if (n.value === 'filter') {
          n.children.filter((n) => n.selected).forEach((n) => {
            if (n.value === 'sex') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.sex = selected
            } else if (n.value === 'industry') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.industry = selected
            } else if (n.value === 'workPlace') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.label).join(' ')
              params.workPlace = selected
            } else if (n.value === 'salary') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.salary = selected
            } else if (n.value === 'jobIntention') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.jobIntention = selected
            } else if (n.value === 'workExp') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.workExp = selected
            } else if (n.value === 'edu') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.value).join(' ')
              params.edu = selected
            } else if (n.value === 'hourseAddress') {
              const selected = n.children.filter((n) => n.checked).map((n) => n.label).join(' ')
              params.hourseAddress = selected
            }
          });
        }
      }
    })
    if (Object.keys(params).length != 0) {
      this.onFilPosition(params);
      this.data.keepFilterData = params; // 保存筛选参数         
    }
  },


  onFilHourly(data) {
    // 重置数据
    this.data.hourlyPage = 1;
    this.data.hourlyList = [];
    this.data.isLoadedHourly = false;
    this.data.isFirstTipHourly = true;
    let tem = {};
    // 处理数据
  },

  onFilPosition(posData) {
    let obj = posData;
    // 重置数据
    this.data.posPage = 1;
    this.data.posList = [];
    this.data.isLoadedPos = false;
    this.data.isFirstTipPos = true;

    // 处理数据
    let tem = {};
    if (obj.sex) {
      tem.sex = Number(obj.sex);
    }
    if (obj.industry) {
      tem.industryId = Number(obj.industry);
    }
    if (obj.workPlace) {
      tem.intentionProvince = '广东省';
      tem.intentionCity = '广州市';
      if (!/区/.test(obj.workPlace)) {
        tem.intentionDistrict = '黄埔区';
        tem.intentionStreet = obj.workPlace;
      } else {
        tem.intentionDistrict = obj.workPlace;
      }
    }
    if (obj.salary) {
      tem.salary = Number(obj.salary);
    }

    if (obj.jobIntention) {
      tem.jobStatus = Number(obj.jobIntention);
    }

    if (obj.workExp) {
      let _we = Number(obj.workExp);
      switch(_we) {
        case 1: tem.workYearUp = 0; tem.workYearDown = 1;break;
        case 3: tem.workYearUp = 1; tem.workYearDown = 3;break;
        case 4: tem.workYearUp = 3; tem.workYearDown = 5;break;
        case 5: tem.workYearUp = 5; tem.workYearDown = 60;break;
      }
    }

    if (obj.edu) {
      switch(obj.edu) {
        case '0':
        case '1':
        case '2': tem.education = 2;break
        case '3': 
        case '4': tem.education = 3;break;
        case '5': tem.education = 5;break;
        case '6': tem.education = 6;break;
        case '7': tem.education = 7;break;
        case '8': tem.education = 8;break;
        case '9': tem.education = 9;break;
      }
    }

    if (obj.hourseAddress) {
      if (!/区/.test(obj.hourseAddress)) {
        tem.homeAddress = '黄埔区-' + obj.hourseAddress;
      } else {
        tem.homeAddress = obj.hourseAddress;
      }
    }
    this.getPosList(tem);
  },

  resetNavSelectStatus() {
    this.data.selectArr.map(m => m.checked = false);
  },

  onFilterNav (e) {
    let index = e.currentTarget.dataset.index;
    this.data.selectArr.map((m, i) => {
      if (i == index) {
        // 判断当前nav是否被选中
        if (m.checked) { // 关闭
          m.checked = false;
          this.setData({
            isOpenHourlyDrop: false
          });
        } else { // 打开
          let isFilterPositon = index == 0 ? true : false;
          m.checked = true;
          if (index == 0) { // 空闲日期
            $wuxCalendar().open({
              value: this.data.filterHourlySpaceTime,
              onChange: (values, displayValues) => {
                console.log(values);
                this.data.filterHourlySpaceTime = values;
                this.setData({isOpenHourlyDrop: false});
                this.resetNavSelectStatus();
                if (values.length != 0) {
                  this.getHourlyList();
                }
              },
              onClose: () => {
                this.setData({ isOpenHourlyDrop: false });
                this.resetNavSelectStatus();
              }
            });
          }
          this.loadHourlyFilterData(index);
          this.setData({
            isOpenHourlyDrop: true,
            isFilterPositon
          });
        }
      } else {
        // 重置其他nav选中状态
        m.checked = false;
      }
    })
  },

  onCloseFilter(e) {
    let role = e.currentTarget.dataset.role;
    if (role == 'parent') {
      this.setData({
        isOpenHourlyDrop: false
      });
      this.resetNavSelectStatus();
    }
  },


  /**
   * 根据条件筛选小时工职位
   */
  onFilterData(e) {
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    let title = e.currentTarget.dataset.title;
    let value = e.currentTarget.dataset.value;


    if (type == 1) { // 居住地
      this.data.filterHourlyHomeAddress.map((m, i) => {
        if (index == i) {
          m.checked = true;
        } else {
          m.checked = false;
        }
      })
      this.data.filterHourlyHA = title;
      this.setData({
        filterList: this.data.filterHourlyHomeAddress
      })
    }

    if (type == 2) { // 意向地点
      this.data.filterHourlyWorkPlace.map((m, i) => {
        if (index == i) {
          m.checked = true;
        } else {
          m.checked = false;
        }
      })
      this.data.filterHourlyWP = title;
      this.setData({
        filterList: this.data.filterHourlyWorkPlace
      })
    }

    if (type == 3) { // 结算方式
      this.data.filterHourlyClearingWay.map((m, i) => {
        if (index == i) {
          m.checked = true;
        } else {
          m.checked = false;
        }
      })
      this.data.filterHourlyCW = value;
      this.setData({
        filterList: this.data.filterHourlyClearingWay
      })
    }
    console.log('index:' + index, 'type:' + type, 'title:' + title, 'value:' + value)
    this.resetNavSelectStatus();
    this.getHourlyList();
  },

  getPosList(obj = {}) {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'resume/search_resume/full',
      method: 'GET',
      data: {
        token: token,
        page:this.data.posPage,
        size: this.data.pageSize,
        name: this.data.inputText ? this.data.inputText : null,
        ...obj
      },
      success: (res) => {
        if (res.rowCount == this.data.posList.length) {
          this.data.isLoadedPos = true;
          return
        }
        this.setData({
          posList: this.data.posList.concat(res.list)
        })
      }
    })
  },

  getHourlyList() {
    let obj = {};
    if (this.data.inputText) {
      obj.position = this.data.inputText;
    }

    if (this.data.filterHourlySpaceTime.length != 0) {
      obj.freeDate = T.formatTime(this.data.filterHourlySpaceTime[0], '-');
    }

    if (this.data.filterHourlyHA) {
      if (!/区/.test(this.data.filterHourlyHA)) {
        obj.homeAddress = '黄埔区-' + this.data.filterHourlyHA;
      } else {
        obj.homeAddress = this.data.filterHourlyHA;
      }
    }

    if (this.data.filterHourlyWP) {
      obj.intentionProvince = '广东省';
      obj.intentionCity = '广州市';
      if (!/区/.test(this.data.filterHourlyWP)) {
        obj.intentionDistrict = '黄埔区';
        obj.intentionStreet = this.data.filterHourlyWP;
      } else {
        obj.intentionDistrict = this.data.filterHourlyWP;
      }
    }

    if (this.data.filterHourlyCW) {
      obj.clearingWay = Number(this.data.filterHourlyCW);
    }
    console.log(obj);
    
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'resume/search_resume/hourly',
      method: 'GET',
      data:{
        token: token,
        // page: this.data.hourlyPage,
        // size: this.data.pageSize,
        ...obj
      },
      success: (res) => {
        if (res.length == 0) {
          this.data.isLoadedPos = true;
          return
        }
        this.setData({
          hourlyList: this.data.hourlyList.concat(res)
        })
      }
    })
  },

  jumpDetails(e) {
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    if (type == 1) { // 全职
      wx.navigateTo({
        url: '../fulltime/detail?id=' + id,
      })
    } else {
      wx.navigateTo({
        url: '../hourly/detail?id=' + id,
      })
    }
  },

  onReachBottom: function() {
    let kid = this.data.kindId;
    if (kid == 0) { // 职位
      if (this.data.isLoadedPos) {
        if (this.data.isFirstTipPos) {
          this.toast('已加载完全部数据了');
        }
        this.data.isFirstTipPos = false;
        return;
      }
      this.data.posPage += 1;
      this.getPosList();
    } else {
      if (this.data.isLoadedHourly) {
        if (this.data.isFirstTipHourly) {
          this.toast('已加载完全部数据了');
        }
        this.data.isFirstTipHourly = false;
        return;
      }
      this.data.hourlyPage += 1;
      this.getHourlyList();
    }
  },

  onPosDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/resume/fulltime/detail?id=' + id,
    })
  }
})